<template>
  <div class="article-editor-container">
    <!-- 编辑器工具栏 -->
    <div class="editor-toolbar">
      <el-button-group>
        <el-tooltip content="保存文章" placement="top">
          <el-button 
            type="primary" 
            @click="saveArticle"
            :loading="loading"
            :disabled="loading">
            <template #icon>
              <el-icon><upload /></el-icon>
            </template>
            保存
          </el-button>
        </el-tooltip>
        <el-tooltip content="预览文章" placement="top">
          <el-button 
            @click="handlePreview"
            :disabled="!article.content">
            <template #icon>
              <el-icon><view /></el-icon>
            </template>
            预览
          </el-button>
        </el-tooltip>
      </el-button-group>
      
      <div class="toolbar-right">
        <el-select 
          v-model="article.categoryId" 
          placeholder="选择分类" 
          style="width: 150px"
          clearable
          filterable
          :disabled="loading">
          <el-option
            v-for="item in categories"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        
        <el-select
          v-model="article.tags"
          multiple
          filterable
          allow-create
          placeholder="选择标签"
          style="width: 200px; margin-left: 10px"
          :disabled="loading">
          <el-option
            v-for="tag in tagOptions"
            :key="tag.value"
            :label="tag.label"
            :value="tag.value">
          </el-option>
        </el-select>
      </div>
    </div>

    <!-- 标题输入 -->
    <el-input
      v-model="article.title"
      placeholder="请输入文章标题"
      class="article-title-input"
      maxlength="100"
      show-word-limit
      :disabled="loading"
      clearable>
      <template #prefix>
        <el-icon><edit /></el-icon>
      </template>
    </el-input>

    <!-- Markdown编辑器 -->
    <mavon-editor
      ref="mdEditor"
      v-model="article.content"
      :toolbars="markdownToolbars"
      :subfield="false"
      :defaultOpen="'edit'"
      :codeStyle="'atom-one-dark'"
      :editable="!loading"
      :scrollStyle="true"
      :ishljs="true"
      @imgAdd="handleImageAdd"
      @save="saveArticle"
      style="height: calc(100vh - 220px)"
      class="markdown-editor"/>

    <!-- 预览对话框 -->
    <el-dialog
      title="文章预览"
      v-model="previewVisible"
      width="80%"
      top="5vh"
      custom-class="preview-dialog"
      :close-on-click-modal="false">
      <div class="preview-content markdown-body" v-html="compiledContent"></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark.css'
import { marked } from 'marked'
import 'github-markdown-css/github-markdown.css'
import { ElMessage, ElLoading } from 'element-plus'
import { Upload, View, Edit } from '@element-plus/icons-vue'
import { 
  getCategoryList, 
  getTagList, 
  addArticle, 
  uploadImage,
  getArticleDetail
} from '@/api/article'
import { useUserStore } from '@/stores/user'

// 配置marked和highlight.js
marked.setOptions({
  breaks: true,
  gfm: true,
  highlight: function(code, lang) {
    const language = hljs.getLanguage(lang) ? lang : 'plaintext'
    return hljs.highlight(code, { language }).value
  }
})

export default {
  name: 'ArticleEditor',
  components: {
    mavonEditor,
    Upload,
    View,
    Edit
  },
  props: {
    Id: {
      type: Number,
      default: null
    }
  },
  setup(props) {
    // 文章数据
    const article = ref({
      title: localStorage.getItem('article_title') || '',
      content: localStorage.getItem('article_content') || '',
      categoryId: localStorage.getItem('article_category') || null,
      tags: JSON.parse(localStorage.getItem('article_tags') || '[]')
    })

    watch(article.value, (newVal) => {
      localStorage.setItem('article_title', newVal.title)
      localStorage.setItem('article_content', newVal.content)
      localStorage.setItem('article_category', newVal.categoryId || '')
      localStorage.setItem('article_tags', JSON.stringify(newVal.tags))
    }, { deep: true })

    // UI状态
    const previewVisible = ref(false)
    const mdEditor = ref(null)
    const loading = ref(false)

    // 分类和标签数据
    const categories = ref([])
    const tagOptions = ref([])

    //获取用户
    const userStore = useUserStore()
    console.log("当前用户信息", userStore.userInfo)
    // Markdown工具栏配置
    const markdownToolbars = {
      bold: true,
      italic: true,
      header: true,
      underline: true,
      strikethrough: true,
      mark: true,
      superscript: true,
      subscript: true,
      quote: true,
      ol: true,
      ul: true,
      link: true,
      imagelink: true,
      image: true,
      code: true,
      table: true,
      fullscreen: true,
      readmodel: true,
      htmlcode: true,
      help: true,
      undo: true,
      redo: true,
      trash: true,
      save: true,
      navigation: true,
      alignleft: true,
      aligncenter: true,
      alignright: true,
      subfield: true,
      preview: true
    }

    // 编译Markdown内容
    const compiledContent = computed(() => {
      return marked.parse(article.value.content || '')
    })

    // 初始化高亮JS
    const initHighlightJS = () => {
      hljs.configure({
        ignoreUnescapedHTML: true,
        languages: ['javascript', 'python', 'java', 'cpp', 'html', 'css', 'sql', 'bash', 'json']
      })
    }

    // 获取分类数据
    const fetchCategories = async () => {
      try {
        loading.value = true
        const { data } = await getCategoryList()
        categories.value = data.map(item => ({
          value: item.id,
          label: item.categoryName
        }))
      } catch (error) {
        console.error('获取分类失败:', error)
        ElMessage.error('获取分类失败，请刷新重试')
      } finally {
        loading.value = false
      }
    }

    // 获取标签数据
    const fetchTags = async () => {
      try {
        loading.value = true
        const { data } = await getTagList()
        tagOptions.value = data.map(item => ({
          value: item.id,
          label: item.tagName
        }))
      } catch (error) {
        console.error('获取标签失败:', error)
        ElMessage.error('获取标签失败，请刷新重试')
      } finally {
        loading.value = false
      }
    }

    // 处理图片上传
    const handleImageAdd = async (pos, file) => {
      console.log("图片上传");
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '图片上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      
      try {
          const response = await uploadImage(file);
          const imageUrl = response.data;
          // 直接插入数据，不检查url字段
          mdEditor.value.$img2Url(pos, imageUrl || '');
          ElMessage.success('图片上传成功');
        } catch (error) {
        console.error('图片上传失败:', error)
        ElMessage.error('图片上传失败，已使用本地预览')
        // 上传失败时使用本地URL预览
        mdEditor.value.$img2Url(pos, URL.createObjectURL(file))
      } finally {
        loadingInstance.close()
      }
    }

    

    // 保存文章
    const saveArticle = async () => {
      if (!article.value.title.trim()) {
        ElMessage.warning('请输入文章标题')
        return
      }
      
      if (!article.value.content.trim()) {
        ElMessage.warning('请输入文章内容')
        return
      }
      
      if (!article.value.categoryId) {
        ElMessage.warning('请选择文章分类')
        return
      }
      
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '文章保存中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      
      try {
        
        const postData = {
          
          title: article.value.title,
          content: article.value.content,
          categoryId: article.value.categoryId,
          tags: article.value.tags,
          email: userStore.userInfo.email
        }
        
        await addArticle(postData)
        ElMessage.success('文章保存成功')
        localStorage.removeItem('article_title')
        localStorage.removeItem('article_content')
        localStorage.removeItem('article_category')
        localStorage.removeItem('article_tags')
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error(error.message || '文章保存失败，请重试')
      } finally {
        loadingInstance.close()
      }
    }

    // 处理预览 - 修改为使用对话框预览
    const handlePreview = () => {
      if (!article.value.content.trim()) {
        ElMessage.warning('没有内容可预览')
        return
      }
      previewVisible.value = true
    }

    // 初始化文章数据（编辑模式）
    const initArticleData = async () => {
      if (!props.Id) return
      
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '加载文章中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      
      try {
        const { data } = await getArticleDetail(props.articleId)
        article.value = {
          title: data.title,
          content: data.content,
          categoryId: data.categoryId,
          tags: data.tags || [],
          creatTime: data.creatTime
        }
      } catch (error) {
        console.error('获取文章详情失败:', error)
        ElMessage.error('获取文章详情失败，请刷新重试')
      } finally {
        loadingInstance.close()
      }
    }

    // 组件挂载时初始化
    onMounted(() => {
      
        initHighlightJS()
        fetchCategories()
        fetchTags()
        initArticleData()
        nextTick(() => {
          setTimeout(() => {
            if (mdEditor.value && mdEditor.value.$refs.toolbar_left) {
              // 用正确的类名查询（.v-icon.image）
              const imageBtn = mdEditor.value.$refs.toolbar_left.$el.querySelector('.op-icon.fa-mavon-picture-o');
              console.log('图片按钮实例是否存在：', imageBtn); // 如果按钮正常，会输出DOM元素
            }
          }, 200); // 延迟200ms，确保按钮渲染
        });
      })

    return {
      article,
      previewVisible,
      categories,
      tagOptions,
      mdEditor,
      markdownToolbars,
      compiledContent,
      handleImageAdd,
      saveArticle,
      handlePreview,
      loading
    }
  }
}
</script>

<style lang="scss" scoped>
:deep(.v-note-wrapper) {
  position: relative;
  z-index: 1 !important; /* 取消编辑器容器的高层级 */
}

/* 精确控制编辑区域 */
:deep(.v-note-wrapper .v-note-panel .v-note-edit.divarea-wrapper) {
  // z-index: 1 !important; /* 设置为较低的值 */
}

.article-editor-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;

  .editor-toolbar {
    padding: 10px 15px;
    background: #f5f7fa;
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .toolbar-right {
      display: flex;
      align-items: center;
    }
  }

  .article-title-input {
    padding: 15px;
    font-size: 18px;
    
    :deep(.el-input__inner) {
      border: none;
      border-bottom: 1px solid #e6e6e6;
      border-radius: 0;
      padding: 10px 0;
      font-size: 18px;
      font-weight: bold;
      
      &:focus {
        border-bottom-color: #409eff;
      }
    }
  }

  .markdown-editor {
    flex: 1;
    border: none;
    
    :deep(.v-note-wrapper) {
      z-index: 1;
    }
  }
}

.preview-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.preview-content {
  padding: 20px;
  overflow-y: auto;
  max-height: 70vh;
  
  &.markdown-body {
    box-sizing: border-box;
    min-width: 200px;
    max-width: 980px;
    margin: 0 auto;
    padding: 45px;
    
    h1, h2, h3, h4, h5, h6 {
      margin: 1em 0;
      color: #333;
      border-bottom: 1px solid #eaecef;
      padding-bottom: 0.3em;
    }
    
    p {
      line-height: 1.8;
      margin: 1em 0;
    }
    
    pre {
      background: #282c34;
      border-radius: 6px;
      padding: 15px;
      overflow: auto;
      
      code {
        color: #abb2bf;
        background: transparent;
      }
    }
    
    img {
      max-width: 100%;
      border-radius: 4px;
    }
    
    blockquote {
      border-left: 4px solid #dfe2e5;
      color: #6a737d;
      padding: 0 1em;
      margin: 0 0 16px 0;
    }
    
    table {
      display: block;
      width: 100%;
      overflow: auto;
      border-spacing: 0;
      border-collapse: collapse;
      
      th, td {
        padding: 6px 13px;
        border: 1px solid #dfe2e5;
      }
      
      tr {
        background-color: #fff;
        border-top: 1px solid #c6cbd1;
        
        &:nth-child(2n) {
          background-color: #f6f8fa;
        }
      }
    }
  }
}
</style>